package com.leyou.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leyou.PageResult;
import com.leyou.ResponseData;
import com.leyou.entity.Spu;
import com.leyou.bo.SpuBo;
import com.leyou.mapper.BrandMapper;
import com.leyou.mapper.CategoryMapper;
import com.leyou.mapper.SpuMapper;
import com.leyou.service.CategoryService;
import com.leyou.service.SpuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;
    @Autowired
    private CategoryService categoryService;

    @Override
    public ResponseData querySpuByPage(Integer page, Integer rows, String key, Boolean saleable) throws Exception {
        // 1、查询SPU
        // 分页,最多允许查100条
        PageHelper.startPage(page, Math.min(rows, 100));
        // 创建查询条件
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        // 是否过滤上下架
        if (saleable != null) {
            criteria.orEqualTo("saleable", saleable);
        }
        // 是否模糊查
        if (StringUtils.isNotBlank(key)) {
            criteria.andLike("title", "%" + key + "%");
        }
        Page<Spu> pageInfo = (Page<Spu>) spuMapper.selectByExample(example);

        // 封装查询结果
        List<SpuBo> spuBoList = new ArrayList<>();
        for (Spu spu : pageInfo.getResult()) {
            // 2.把Spu转换为SpuBo
            SpuBo spuBo = new SpuBo();
            // 属性拷贝
            BeanUtils.copyProperties(spu, spuBo);

            // 3.查询商品的分类名称。例如：手机/电子产品/通讯设备
            List<Long> ids = Arrays.asList(spuBo.getCid1(), spuBo.getCid2(), spuBo.getCid3());
            List<String> categories = categoryService.getCategoryNameByIds(ids);
            // 将分类名称拼接后存入
            String cname = StringUtils.join(categories, "/");
            spuBo.setCname(cname);

            // 4.查询spu品牌名称
            String brandName = brandMapper.selectByPrimaryKey(spu.getBrandId()).getName();
            spuBo.setBname(brandName);

            // 5.封装进集合
            spuBoList.add(spuBo);
        }

        // Lambda 内部只能处理异常而不能抛异常

        PageResult<List<SpuBo>> pageResult = new PageResult<>(pageInfo.getTotal(), (long) pageInfo.getPages(), spuBoList);
        return ResponseData.ok(pageResult);
    }

    @Override
    public Spu querySpuById(Long id) throws Exception {
        return spuMapper.selectByPrimaryKey(id);
    }
}
